<?php

App::import('Sanitize');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::import('Component', 'Session');
App::import('Model', 'Task');

class TasksController extends AppController {

    public $components = array('Session', 'RequestHandler');
    public $helpers = array('Html', 'Form');

    /**
     * The function checks for user permssions
     * 
     * The function checks whether the user can view tasks in this account or not,
     *  it also checks if he is logged in any account
     * @return string 
     * @author Nada
     */
    function _checkPermission() {
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $isDeleted = $this->Task->getDeleted($userID);
        if ($isDeleted == true) {
            $this->Session->setFlash('Your account was deleted by an admin');
            $this->redirect(array('controller' => 'users', 'action' => 'logout'));
        }
        if ($accID == null) {
            $this->Session->setFlash('You are not logged in into any account!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
            return "nullAccount";
        }
        $permissionLevel = $this->Task->getPermissionLevel($accID, $userID);
        if (!(($permissionLevel == 1) || ($permissionLevel == 2) || ($permissionLevel == 3))) {
            $this->Session->setFlash("You are not authorized to view this page! ");
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
            return "invalid permissions";
        }
    }

    /**
     *
     * @param type $id the ID of the task to be viewed
     * @author Nada
     * @access public
     * The function creates a view for the given task ID 
     */
    function view($id = null) {

        $this->_checkPermission();
        $this->layout = 'tasksLayout';
        $this->Task->id = $id;
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $task = $this->Task->read();
        if ($task['Task']['accID'] != $accID) {
            $this->Session->setFlash('No such task for this account!');
            return
                    $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        $sentByID = $task['Task']['sentBy'];
        $sentToID = $task['Task']['sentTo'];
        $userPermission = $this->Task->getUserPermission($task['Task']['taskID'], $userID);

        if ($userPermission == null) {
            $this->Session->setFlash('You dont have enough permissions to view this page');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        $users = $this->Task->getTaskUsers($task['Task']['taskID']);

        for ($counter = 0; $counter < sizeof($users); $counter++) {
            $userNameString = $this->Task->getTweetAuthor($users[$counter]['tasks_has_users']['userID']);
            $users[$counter]['tasks_has_users']['username'] = $userNameString[0]['User']['username'];
            $users[$counter]['tasks_has_users']['image'] = $userNameString[0]['User']['image'];
        }
        $this->set('users', $users);
        $this->set('userID', $userID);
        $sentByData = $this->Task->getTweetAuthor($sentByID);
        $sentToData = $this->Task->getTweetAuthor($sentToID);
        $this->set('sentToData', $sentToData);
        $this->set('sentByData', $sentByData);
        $taskStatus = $task['Task']['status'];
        $this->set('taskStatus', $taskStatus);
        $this->set('taskID', $id);
        $this->set('userID', $userID);
        $this->set('isAuthor', $this->Task->isAuthor($task['Task']['taskID'], $userID));
        $this->set('isAssignee', $this->Task->isAssignee($task['Task']['taskID'], $userID));
        $sentByUserName = $this->Task->getUserName($task['Task']['sentBy']);
        $task['Task']['sentBy'] = $sentByUserName[0]['User']['username'];
        $this->set('task', $task);
        $messages = $this->Task->getMessages($id);
        $returnedTweet = $this->Task->getTweet($task['Task']['postID']);
        $this->set('returnedTweet', $returnedTweet);
        $i = 0;
        foreach ($messages as $message) {
            $messageAuthor = $this->Task->getUserName($message['Message']['userID']);
            $messages[$i]['Message']['userID'] = $messageAuthor[0]['User']['username'];
            $i++;
        }
        $this->set('messages', $messages);
        $tweetIsMention = $returnedTweet[0]['Tweet']['isMention'] == 1;
        if ($tweetIsMention) {
            $authorAccID = $returnedTweet[0]['post']['accID'];
            $tweetAuthor = $this->Task->getMentionAuthor($authorAccID);
            $this->set('tweetAuthor', $tweetAuthor[0]['Account']['twitterName']);
            $this->set('authorImage', $tweetAuthor[0]['Account']['image']);
        } else {
            $tweetAuthor = $this->Task->getTweetAuthor($returnedTweet[0]['post']['userID']);
            $tweetAuthorString = $tweetAuthor[0]['User']['username'];
            if ($tweetAuthorString == "") {
                $accID = $returnedTweet[0]['post']['accID'];
                $tweetAuthorString = $this->Task->getMentionAuthor($accID);
            }
            $this->set('tweetAuthor', $tweetAuthorString[0]['Account']['twitterName']);
            $this->set('authorImage', $tweetAuthor[0]['User']['image']);
        }
        $username = $this->Task->getUserName($userID);
        $this->set('userName', $username[0]['User']['username']);

        if ($this->request->is('post')) {
            if ($task['Task']['status'] == 'incomplete') {


                if ($this->request->data['Message']['messageText'] == "") {
                    $this->Session->setFlash("Please enter a message");
                } else {
                    if (ClassRegistry::init('Message')->save($this->request->data)) {
                        $this->Session->setFlash('Your comment has been posted');
                        if ($this->request->data['Message']['status'] == 1) {
                            $this->Task->completeTask($id);
                        }
                        return $this->redirect(array('action' => 'view', $id));
                    } else {
                        $this->Session->setFlash('Unable to add your Message.');
                    }
                }
            } else {
                $this->Session->setFlash("This task is already completed.");
            }
        }
    }

    /**
     * @access public
     * @author Nada
     * a function that provides the users view with the array of users working within a company 
     */
    function viewUsers() {
        $this->_checkPermission();
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $this->layout = 'tasksLayout';
        $y;
        $i = 0;
        $users = $this->Task->getUsers($accID, $userID);
        if ($users == null) {
            $this->Session->setFlash('There are no other users in this company, you are in your own!');
            $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        foreach ($users as $user) {
            $y[$i]['username'] = $user['users']['username'];
            $y[$i]['image'] = $user['users']['image'];
            $y[$i]['twitter'] = $user['users']['twitter'];
            $y[$i]['facebook'] = $user['users']['facebook'];
            $i++;
        }
        $this->set('user', $y);
    }

    /**
     * The function creates a view of all tasks
     * @return void 
     * @author Nada
     */
    function viewAll() {
        if ($this->_checkPermission() == "nullAccount") {
            return $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $this->set('user', $userID);
        $this->layout = 'tasksLayout';
        $tasks = $this->Task->getTasks($userID, $accID);
        $i = 0;
        if ($tasks == null)
            $this->Session->setFlash('You don\'t have any tasks!');
        foreach ($tasks as $task) {

            $userName = $this->Task->getTweetAuthor($tasks[$i]['tasks']['sentBy']);
            $tasks[$i]['tasks']['sentBy'] = $userName[0]['User']['username'];
            $i++;
        }
        $this->set('userID', $userID);
        $this->set('tasks', $tasks);
        if ($this->request->data != null) {
            if ($this->request->data['Task']['action'] == 'accept') {
                $this->Task->id = $this->request->data['Task']['taskID'];
                $this->Task->acceptTask($this->request->data['Task']['taskID'], $userID);
                $this->Session->setFlash('Task accepted!');
                return $this->redirect(array('action' => 'view', $this->request->data['Task']['taskID']));
            }
            if ($this->request->data['Task']['action'] == 'reject') {
                $this->Task->rejectTask($this->request->data['Task']['taskID'], $userID);
                $this->Session->setFlash('Task rejected!');
                return $this->redirect(array('action' => 'viewAll'));
            }
            if ($this->request->data['Task']['action'] == 'end') {
                $this->Session->setFlash('Task completed!');
                $this->Task->completeTask($this->request->data['Task']['taskID']);
                return $this->redirect(array('action' => 'view', $this->request->data['Task']['taskID']));
            } if ($this->request->data['Task']['action'] == 'reassign') {
                $this->redirect(array('action' => 'reassign', $this->request->data['Task']['taskID']));
                return 'reassign';
            }
        }
    }

    /**
     * The function is used to reassign tasks.
     * 
     * The function will generata a view of users with checkboxes, the user will pick
     *  whoever he wants to reassign the task to and submit.
     *
     * @param int $taskID
     * @return void 
     * @author Nada
     */
    function reassign($taskID = null) {
        $this->layout = 'tasksLayout';
        $this->_checkPermission();
        $userID = $this->Auth->User('userID');
        $this->Task->id = $taskID;
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        // check if the user is enrolled in the task and not the owner
        $task = $this->Task->read();
        $taskID = $task['Task']['taskID'];
        if ($task == null) {
            $this->Session->setFlash('No such task for this account!');
            return $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        if ($task['Task']['accID'] != $accID) {
            $this->Session->setFlash('No such task for this account!');
            return $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
        if (!$this->Task->isEnrolled($taskID, $userID)) {
            $this->Session->setFlash('You are not allowed to reassign this task.');
            return $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }

        $accID = $this->Auth->User('accID');
        $users = $this->Task->getAvailableUsers($taskID, $accID);
        if ($users == null) {
            $this->Session->setFlash("There are no remaining users to reassign the task to!");
            return $this->redirect(array('action' => 'viewAll'));
        }
        $this->set('users', $users);
        if ($this->request->data != null) {
            if ($this->request->data['Task']['sentTo'] != null) {
                if ($this->request->data['Task']['action'] == 'reassign') {
                    $selectedUsers = $this->request->data['Task']['sentTo'];
                    $j = 0;
                    $allUsersValid = true;
                    foreach ($selectedUsers as $selectedUser) {
                        $isDeleted = $this->Task->getDeleted($selectedUser);
                        if (($this->Task->isEnrolled($taskID, $selectedUser) == true) || ($isDeleted == true)) {
                            $allUsersValid = false;
                            break;
                        }
                    }
                    if ($allUsersValid) {
                        $this->Task->reassign($taskID, $userID, $selectedUsers);
                        $this->Session->setFlash("Task reassigned");
                        $this->redirect(array('action' => 'viewAll'));
                        return "task reassigned";
                    } else {
                        $this->Session->setFlash("Your task was not reassigned, you selected a user who already got reassigned to this task before or has been deleted!");
                        $this->redirect(array('action' => 'viewAll'));
                        return 'users not valid';
                    }
                }
            } else {
                $this->Session->setFlash("Please choose a user!");
                return "empty users";
            }
        }
    }

    /**
     * @author Nada
     * a function which sets the add task view 
     * @access public
     * @return void
     */
    function addTask($id = null) {
        $this->_checkPermission();
        $this->layout = 'tasksLayout';
        $userID = $this->Auth->User('userID');
        $accID = $this->Auth->User('accID');
        $accountName = $this->Task->getAccountName($accID);
        $accountNameString = "@" . $accountName[0]['accounts']['twitterName'];
        if ($accID != null) {
            $this->set('userID', $userID);
            $this->set('accID', $accID);
            $returnedTweet = $this->Task->getTweet($id);
            if ($returnedTweet != null) {
                $tweetIsMention = $returnedTweet[0]['Tweet']['isMention'] == 1;
                $x = $returnedTweet[0]['post']['text'];
                if ($tweetIsMention && strpos($returnedTweet[0]['post']['text'], $accountNameString) !== false) {
                    $authorAccID = $returnedTweet[0]['post']['accID'];
                    $tweetAuthor = $this->Task->getMentionAuthor($authorAccID);
                    $this->set('tweetAuthor', $tweetAuthor[0]['Account']['twitterName']);
                    $this->set('authorImage', $tweetAuthor[0]['Account']['image']);
                } else {
                    if ($returnedTweet[0]['post']['accID'] !== $accID) {
                        $this->Session->setFlash("No such tweet in this account");
                        return $this->redirect(array('controller' => 'users', 'action' => 'index'));
                    }
                    $tweetAuthor = $this->Task->getTweetAuthor($returnedTweet[0]['post']['userID']);
                    $tweetAuthorString = $tweetAuthor[0]['User']['username'];
                    $this->set('tweetAuthor', $tweetAuthorString);
                    if ($tweetAuthorString == "") {
                        $tweetAuthorString = $this->Task->getMentionAuthor($returnedTweet[0]['post']['accID']);
                        $this->set('tweetAuthor', $tweetAuthorString[0]['Account']['twitterName']);
                    }
                    $this->set('authorImage', $tweetAuthor[0]['User']['image']);
                }
                $this->set('tweetDate', $returnedTweet[0]['post']['time']);
                $y;
                $i = 0;
                $users = $this->Task->getUsers($accID, $userID);
                if ($users == null) {
                    $this->Session->setFlash("there is no one working within this company with you, you are on your own!");
                    return $this->redirect(array('controller' => 'users', 'action' => 'index'));
                }
                foreach ($users as $user) {
                    $y[$i]['name'] = $user['users']['username'];
                    $y[$i]['image'] = $user['users']['image'];
                    $y[$i]['userID'] = $user['users']['userID'];
                    $i++;
                }
                $this->set('user', $y);
                $this->set('tweet', $returnedTweet);
                $this->set('tweetID', $id);
                $userIDSQL = $this->request->data['Task']['sentTo'];
                if ($this->request->is('post')) {
                    if ($userIDSQL == null || $this->request->data['Task']['originalMessage'] == null) {
                        if ($userIDSQL == null) {
                            $this->Session->setFlash("Please choose a  user!");
                        } else {
                            $this->Session->setFlash("Please enter a message");
                        }
                    } else {

                        // $this->request->data['Task']['sentTo'] = $userIDSQL[0][0]['User']['userID'];
                        $this->request->data['Task']['sentTo'] = $userIDSQL[0];
                        $valid = true;
                        foreach ($userIDSQL as $id) {
                            $permissionLevel = $this->Task->getPermissionLevel($accID, $id);
                            $isDeleted = $this->Task->getDeleted($id);
                            if (!((($permissionLevel == 1) || ($permissionLevel == 2) || ($permissionLevel == 3)) && ($isDeleted == false))) {
                                $valid = false;
                                break;
                            }
                        }
                        if ($valid == true) {
                            if ($this->Task->save($this->request->data)) {

                                $this->Task->addUsers($this->Task->id, $userIDSQL);
                                $this->Session->setFlash('Your task has been added!');
                                return $this->redirect(array('action' => 'viewAll'));
                            } else {
                                $this->Session->setFlash('Unable to add your task, the users you selected are not valid anymore');
                                return $this->redirect(array('action' => 'viewAll'));
                            }
                        } else {
                            $this->Session->setFlash('You have chosen to assign task to a user who is not working on this account anymore.');
                        }
                    }
                }
            } else {
                $this->Session->setFlash('No such tweet for the current account!');
                return $this->redirect(array('controller' => 'users', 'action' => 'index'));
            }
        } else {
            $this->Session->setFlash('You are not currently assigned to any account');
            return $this->redirect(array('controller' => 'users', 'action' => 'index'));
        }
    }

}

